#include "modulelistmodel.h"
#include <QStandardItem>
#include <QString>
#include "types.h"

ModuleListModel::ModuleListModel(const QList<Module> &module, QObject *parent)
                    : QAbstractListModel(parent), moduleList(module)
{
}

ModuleListModel::~ModuleListModel()
{
}

int ModuleListModel::rowCount(const QModelIndex &parent) const
{
  UNUSED_ARGUMENT(parent);
  return moduleList.count();
}

QVariant ModuleListModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    if (index.row() >= moduleList.size())
        return QVariant();

    if (role == Qt::DisplayRole) {
        Module m = moduleList.at(index.row());
        QVariant qvarModule;
        qvarModule.setValue<QString>(m.data());
        return qvarModule;
    }
    else
        return QVariant();
}

QVariant ModuleListModel::headerData(int section, Qt::Orientation orientation, int role) const
{
  UNUSED_ARGUMENT(section);
  UNUSED_ARGUMENT(orientation);
  UNUSED_ARGUMENT(role);

  return QVariant();
}


Qt::ItemFlags ModuleListModel::flags(const QModelIndex &index) const
{
    if (!index.isValid())
        return Qt::ItemIsEnabled;

    return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
}


bool ModuleListModel::setData(const QModelIndex &index,
                              const QVariant &value, int role)
{
    if (index.isValid() && role == Qt::EditRole) {

        moduleList.replace(index.row(), value.value<Module>());
        emit dataChanged(index, index);
        return true;
    }

    return false;
}


bool ModuleListModel::insertRows(int position, int rows, const QModelIndex &parent)
{
  UNUSED_ARGUMENT(parent);
  beginInsertRows(QModelIndex(), position, position+rows-1);

  for (int row = 0; row < rows; ++row) {
    moduleList.insert(position, Module());
  }

  endInsertRows();
  return true;
}


bool ModuleListModel::removeRows(int position, int rows, const QModelIndex &parent)
{
  UNUSED_ARGUMENT(parent);
  beginRemoveRows(QModelIndex(), position, position+rows-1);

  for (int row = 0; row < rows; ++row) {
    moduleList.removeAt(position);
  }

  endRemoveRows();
  return true;
}
